<template>
  <div class="app-list-page">
    <a-page-header title="企业专属机器人" style="padding-left: 20px">
      <template #extra>
        <a-button
        :disabled="$store.state.user.userIdentity==0"
          type="primary"
          @click="addAppClick"
          style="border-radius: 6px"
          v-if="!notMember"
        >
          <PlusOutlined />新增机器人
        </a-button>
      </template>
      <div style="color: #666">
        所有机器人都在这里显示，支持创建多个机器人，推荐一个机器人仅落地一个相同主题的业务场景
      </div>
    </a-page-header>
    <template v-if="showPage">
      <template v-if="notMember">
        <a-card :bordered="false" style="margin: 0 20px">
          <div class="flex flex-col align-center py-30">
            <WarningFilled style="color: #faad14; font-size: 64px" />
            <div class="mt-20 fs-24">此能力仅 团队/企业 成员可用</div>
            <div class="mt-10 text-gray-6">
              当前身份：{{ currentTeam.id ? "团队/企业" : "个人" }}
            </div>
            <a-row class="mt-20 flex justify-center">
              <a-button
                type="primary"
                style="border-radius: 6px"
                @click="changeTeamPopoverVisible(true)"
              >
                <template #icon><SwapOutlined /></template>
                切换 团队/企业
              </a-button>
              <a-button
                type="primary"
                class="ml-20"
                style="border-radius: 6px"
                @click="addTeamVisible = true"
              >
                <template #icon><PlusCircleOutlined /></template>
                创建 团队/企业
              </a-button>
            </a-row>
          </div>
        </a-card>
      </template>
      <template v-else>
        <div class="step-wrap">
          <a-steps :current="-1">
            <a-step>
              <template #title
                >训练AI
                <a-button type="link" style="margin: 0" @click="toKnowledgeBase"
                  >去训练</a-button
                >
              </template>
              <template #description>
                <span>上传知识库让AI运行学习和训练</span>
              </template>
            </a-step>
            <a-step>
              <template #title>创建机器人</template>
              <template #description>
                <span>创建机器人完成个性化设置并关联知识库</span>
              </template>
            </a-step>
            <a-step>
              <template #title>开始对话</template>
              <template #description>
                <span>直接开始对话或选择发布的方式，让机器人为你工作</span>
              </template>
            </a-step>
          </a-steps>
        </div>
        <div class="app-list-wrap" v-if="appList.length > 0">
          <a-row class="app-list">
            <a-col
              :xs="12"
              :sm="12"
              :md="12"
              :lg="8"
              :xl="6"
              v-for="(item, index) of appList"
              :key="index"
            >
              <div class="app-item">
                <div style="display: flex; align-items: center">
                  <img
                    :src="item.app_logo"
                    alt=""
                    class="app-item-logo"
                    v-if="item.app_logo"
                  />
                  <div class="app-item-name">{{ item.app_name }}</div>
                </div>

                <div class="app-item-intro">{{ item.app_desc }}</div>

                <div class="app-item-controls">
                  <a-button
                  :disabled="$store.state.user.userIdentity==0"
                    class="app-item-setting"
                    @click.stop="editAppClick(item)"
                  >
                    设置
                  </a-button>
                  <a-button class="app-item-goChat" @click="onAppClick(item.id)">
                    开始对话
                  </a-button>
                </div>

                <CloseCircleOutlined
                  class="close-button"
                  @click.stop="deleteAppClick(item)"
                />
              </div>
            </a-col>
          </a-row>
          <div class="pagination-wrap">
            <a-pagination
              :total="total"
              :show-total="(total) => `共 ${total} 个`"
              :page-size="pageSize"
              v-model:current="page"
            />
          </div>
        </div>
        <div class="empty-wrap" v-if="noAppData">
          <a-empty description="暂无企业专属机器人，快去添加吧" />
        </div>
      </template>
    </template>

    <AddTeam
      :visible="addTeamVisible"
      @onClose="addTeamVisible = false"
      @success="addTeamSuccess"
      :business="1"
    />

    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />

    <a-modal
      :visible="addAppVisible"
      title="新增机器人"
      centered
      :width="500"
      @cancel="addAppVisible = false"
      @ok="onAddSubmit"
      ok-text="保存"
      :zIndex="1002"
    >
      <div class="modal-content">
        <a-form-item label="机器人名称">
          <a-input v-model:value="editAppName" placeholder="请输入机器人名称" />
        </a-form-item>
        <a-form-item label="机器人图标">
          <template #extra>
            <div style="font-size: 12px">尺寸：120*120px</div>
          </template>
          <a-upload
            :action="$utils.imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            v-model:file-list="logoList"
            @change="handleLogoUpload"
            :multiple="true"
            name="image"
            :data="{ dir: 'work_ai' }"
            accept="image/*"
            list-type="picture-card"
          >
            <div v-if="!logoList.length">
              <PlusOutlined />
              <div>上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="机器人简介">
          <a-textarea
            v-model:value="editAppDesc"
            placeholder="请输入机器人简介"
            :rows="4"
          />
        </a-form-item>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  inject,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message } from "ant-design-vue";
import {
  WarningFilled,
  PlusCircleOutlined,
  SwapOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  CloseCircleOutlined,
} from "@ant-design/icons-vue";
import AddTeam from "@/components/AddTeam/index.vue";
import { useTeam, useTeamState } from "@/hooks/team";

export default defineComponent({
  name: "Create",
  components: {
    WarningFilled,
    PlusCircleOutlined,
    SwapOutlined,
    PlusOutlined,
    AddTeam,
    CloseCircleOutlined,
  },

  setup() {
    const route = useRoute();
    const router = useRouter();
    const changeTeamPopoverVisible = inject(["changeTeamPopoverVisible"]);

    const state = reactive({
      loginVisible: false,
      showPage: false,
      addTeamVisible: false,
      notMember: false,

      total: 0,
      page: 1,
      pageSize: 12,
      appList: [],
      tableLoading: false,

      addAppVisible: false,
      editAppName: "",
      logoList: [],
      editAppDesc: "",
      editAppLogo: "",
      noAppData: false,
      app_numbers: 1,
    });

    const { currentTeam } = useTeam();
    const teamState = useTeamState();

    const getList = () => {
      state.tableLoading = true;
      state.noAppData = false;
      request
        .get("/work_ai", "/user/team/app", {
          page: state.page,
          pageSize: state.pageSize,
          team_id: store.state.user.teamId,
        })
        .then((res) => {
          state.total = res.total;
          state.appList = res.list;
          state.tableLoading = false;
          state.app_numbers = res.app_numbers;

          if (res.list.length == 0) {
            state.noAppData = true;
          }
        });
    };

    const init = () => {
      state.page = 1;
      state.pageSize = 20;
      state.total = 0;
      state.appList = [];

      if (store.state.user.teamId) {
        getList();
      }
    };

    const notMember = computed(() => {
      return !store.state.user.teamId;
    });

    utils.checkLogin().then((isLogin) => {
      if (!isLogin) {
        state.loginVisible = true;
        return;
      }
      state.showPage = true;
      init();
    });

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    const addTeamSuccess = async () => {
      state.addTeamVisible = false;
      await teamState.execute();
      init();
    };

    const addAppClick = () => {
      if (state.appList.length >= state.app_numbers) {
        Modal.error({
          content: () =>
            `您只能添加 ${state.app_numbers} 个机器人，已经使用完。请联系客服增加。`,
        });
        return;
      }

      state.editAppName = "";
      state.logoList = [];
      state.editAppDesc = "";
      state.editAppLogo = "";
      state.addAppVisible = true;
    };

    // 上传图片(应用图标)
    const handleLogoUpload = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      state.logoList = resFileList;
      if (state.logoList.length) {
        state.editAppLogo = state.logoList[0].url;
      } else {
        state.editAppLogo = "";
      }
    };

    const onAddSubmit = () => {
      if (!state.editAppName) {
        message.error("机器人名称不能为空");
        return;
      }

      let requestType = "post";
      let url = "/user/team/app";
      let params = {
        app_name: state.editAppName,
        team_id: store.state.user.teamId,
      };
      if (state.editAppDesc) {
        params.app_desc = state.editAppDesc;
      }
      if (state.editAppLogo) {
        params.app_logo = state.editAppLogo;
      }
      request[requestType]("/work_ai", url, {
        ...params,
      }).then((res) => {
        message.success("保存成功");
        state.addAppVisible = false;
        getList();
      });
    };

    // 删除
    const deleteAppClick = (item) => {
      Modal.confirm({
        title: () => `确定要删除${item.app_name}吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/work_ai", "/user/team/app", {
              id: item.id,
            })
            .then((res) => {
              message.success("删除成功");
              state.page = 1;
              getList();
            });
        },
      });
    };

    const onAppClick = (id) => {
      router.push(`/chatModel/appChat/${id}`);
    };

    const editAppClick = (item) => {
      router.push({
        name: "TrainingAppDetail",
        query: {
          id: item.id,
        },
      });
    };

    const toKnowledgeBase = () => {
      router.push({
        name: "TrainingKnowledgeBase",
      });
    };

    watch(
      () => store.state.user.teamId,
      (val) => {
        init();
      }
    );

    return {
      ...toRefs(state),
      loginCallback,
      changeTeamPopoverVisible,
      addTeamSuccess,
      deleteAppClick,
      onAppClick,

      addAppClick,
      onAddSubmit,
      notMember,
      currentTeam,

      handleLogoUpload,
      editAppClick,
      toKnowledgeBase,
    };
  },
});
</script>

<style lang="less" scoped>
.app-list-page :deep(.ant-page-header-content) {
  padding-top: 0px;
}

.app-list-page {
  width: 100%;
  height: 100%;
  padding: 10px;

  .ant-page-header-content {
    padding-top: 0px;
  }

  .step-wrap {
    background-color: #f7f0ff;
    padding: 20px 40px;
    border-radius: 8px;
    border: 1px solid rgba(122, 70, 252, 0.3);
    margin: 0 20px;

    :deep(.ant-steps-item-title) {
      color: #333 !important;

      &::after {
        background-color: #ddd !important;
      }
    }

    :deep(.ant-steps-item-description) {
      max-width: 325px;
      margin-top: 5px;
    }

    :deep(.ant-steps-item-icon) {
      background-color: #f0ecf9;
      border-color: #ddd;

      .ant-steps-icon {
        color: #333 !important;
      }
    }
  }

  .app-list-wrap {
    .app-list {
      padding: 20px 0 40px 20px;
      .app-item {
        height: 190px;
        padding: 15px 20px;
        background-color: #fff;
        border-radius: 12px;
        margin-right: 20px;
        margin-bottom: 20px;
        // cursor: pointer;
        transition: 0.2s ease;
        box-shadow: 0 0px 10px #193e7b14;
        position: relative;

        &:hover {
          // -webkit-transform: translateY(-3px);
          // -ms-transform: translateY(-3px);
          // transform: translateY(-3px);
          -webkit-transition: all 0.5s ease-out;
          transition: all 0.5s ease-out;
          // background-color: #f3f0ff;

          .close-button {
            display: block;
          }
        }

        .app-item-logo {
          width: 40px;
          height: 40px;
          object-fit: cover;
          margin-right: 15px;
        }

        .app-item-name {
          font-size: 18px;
        }

        .app-item-intro {
          margin-top: 10px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          height: 44px;
        }

        .close-button {
          position: absolute;
          top: -5px;
          right: -5px;
          font-size: 18px;
          color: #666;
          display: none;
          -webkit-transition: all 0.5s ease-out;
          transition: all 0.5s ease-out;
        }

        .app-item-controls {
          display: flex;
          align-items: center;
          height: 80px;
          padding: 20px 0;

          .app-item-setting {
            color: @primary-color;
            height: 100%;
            border: 1px solid #eee;
            display: flex;
            justify-content: center;
            align-items: center;
            flex: 1;
            border-radius: 8px;
            cursor: pointer;
            margin-right: 10px;
          }

          .app-item-goChat {
            color: @primary-color;
            height: 100%;
            background-color: #f7f0ff;
            display: flex;
            justify-content: center;
            align-items: center;
            flex: 1;
            border-radius: 8px;
            cursor: pointer;
            margin-left: 10px;
          }
        }
      }
    }

    .pagination-wrap {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-right: 20px;
    }
  }

  .empty-wrap {
    width: 100%;
    display: flex;
    justify-content: center;
    padding-top: 150px;
  }
}
</style>
